<?php

namespace app\merchant\controller;

use app\common\model\FreightModel;
use think\Db;
use think\Request;

class Freight extends Common
{
    //运费模板列表图
    public function index()
    {
        $page_number = input('post.page_number');
        if(empty($page_number)){
            $page_number = 10;
        }
        $where['freight_merchant_id'] = session('merchant.merchant_id');
        $where['freignt_is_delete'] = '0';
        //获取快递模板的列表
        $data['freight_list'] = FreightModel::freight_sel($where, $page_number);
        foreach($data['freight_list'] as $k => $v){
            $namelist = array();
            if($v['freight_tpl_type'] == 1){
                $data['freight_list'][$k]['freight_first_price'] = 0;
                $data['freight_list'][$k]['freight_continued_price'] = 0;
                if($v['freight_is_type'] ==3){
                    $res = Db::table('freight_class')->field('province_name,freight_is_select')->where('freight_id', 'eq', $v['freight_id'])->group('province_name')->select();
                    foreach($res as $key => $vel){
                        if($vel['freight_is_select'] == 1){
                            $namelist[$key] = $vel['province_name'];
                        }else{
                            $relt = Db::table('freight_class')->field('city_name')->where(['freight_id' => $v['freight_id'],'province_name' => $vel['province_name']])->select();
                            $arr = [];
                            foreach($relt as $ke => $ve){
                                $arr[] = $ve['city_name'];
                            }
                            $city = implode(",",$arr);
                            $namelist[$key] = $vel['province_name']."(".$city.")";
                        }
                    }
                    $data['freight_list'][$k]['date'] = implode(",",$namelist);
                }elseif($v['freight_is_type'] ==2){
                    $data['freight_list'][$k]['date'] = "全国包邮（除新疆,西藏,内蒙古）<br />新疆<br />西藏<br />内蒙古";
                    $details = Db::table('freight_class')->field('province_name, freight_first_price, freight_continued_price')->where(['freight_id' => $v['freight_id']])->select();
                    $arr = [];
                    foreach ($details as $detail) {
                        if ($detail['province_name'] == '新疆维吾尔自治区') {
                            $arr[0] = [$detail['freight_first_price'], $detail['freight_continued_price']];
                        }
                        if ($detail['province_name'] == '西藏自治区') {
                            $arr[1] = [$detail['freight_first_price'], $detail['freight_continued_price']];
                        }
                        if ($detail['province_name'] == '内蒙古自治区') {
                            $arr[2] = [$detail['freight_first_price'], $detail['freight_continued_price']];
                        }
                    }
                    if(!empty($arr))
                    {
                    $data['freight_list'][$k]['freight_first_price'] .= "<br />" . $arr[0][0] . "<br />" . $arr[1][0] . "<br />" . $arr[2][0];
                    $data['freight_list'][$k]['freight_continued_price'] .= "<br />" . $arr[0][1] . "<br />" . $arr[1][1] . "<br />" . $arr[2][1];
                    }
                } elseif($v['freight_is_type'] ==1) {
                    $data['freight_list'][$k]['date'] = "全国包邮";
                }

            } elseif($v['freight_tpl_type'] == 2){
                $relt = Db::table('freight_class')->field('city_name,region_name,freight_door_cost')->where('freight_id', $v['freight_id'])->select();
                $areas = '';
                foreach ($relt as $value) {
                    $areas .= "{$value['city_name']}：{$value['region_name']}" . "<br />";
                }
                $data['freight_list'][$k]['date'] = $areas;
                $data['freight_list'][$k]['freight_door_cost'] = $value['freight_door_cost'];
            }
        }
        $data['page'] = $data['freight_list']->render();
        return view('fare',['data' => $data]);
    }

    //添加运费模板页面
    public function add(){
        return view('addfare');
    }

    public function edit()
    {
        $id = input('id');
        $freight = DB::name('freight')->where('freight_id', $id)->find();
        if ($freight['freight_merchant_id'] != session('merchant.merchant_id')) {
            exit('403');
        }
        $details = [];
        $citys = [];
        $cityIds = '';
        if ($freight['freight_is_type'] == 2) {
            $details = DB::name('freight_class')->where('freight_id', $id)->field('freight_first_price, freight_continued_price')->select();
        }
        if ($freight['freight_is_type'] == 3) {
            $details = DB::name('freight_class')->where('freight_id', $id)->field('city_name, city_id')->select();
            foreach ($details as $detail) {
                $city = DB::name('cities')->where('city', $detail['city_name'])->find();
                $citys[] = $city['city'];
            }
            $cityIds = $detail['city_id'];
        }
        return view('editfare', ['freight' => $freight, 'details' => $details, 'citys' => implode(',', $citys), 'city_ids' => $cityIds]);
    }

    /**
     * 添加上门运费模板页面
     */
    public function homeService()
    {
        return view('homeservice');
    }

    //添加运费模板页面
    public function do_add(){
        $data['freight_name'] = input('post.freight_name');
        $data['freight_tpl_type'] = '1';
        $data['freight_merchant_id'] = session('merchant.merchant_id');
        $data['freight_is_type'] = input('post.is_type');
        $data['freight_first_price'] = input('post.first_pay');
        $data['freight_continued_price'] = input('post.xu_pay');
        $data['freight_create_time'] = time();
        $ret = Db::table('freight')->insertGetId($data);
        $province_name = input('post.arr1/a');
        $city_name = input('post.arr2/a');
        foreach($province_name as $k => $v){
            foreach($city_name as $ke => $ve){
                if($v['province_id'] == $ve['province_id']){
                    $date['freight_id'] = $ret;
                    $date['province_name'] = $v['province_name'];
                    $date['city_name'] = $ve['city_name'];
                    $date['freight_is_select'] = $v['is_select'];
                    Db::table('freight_class')->insert($date);
                }
            }
        }
        if(!$ret){
            return returnJson(0, '添加自提点失败');
        }
        return returnJson(1, '添加自提点从成功');
    }

    /**
     *  添加快递模板
     */
    public function addExpress()
    {
        $data = Request::instance()->post();
        $data['freight_merchant_id'] = session('merchant.merchant_id');
        $data['freight_tpl_type'] = 1;
        $data['freight_create_time'] = $data['freight_update_time'] = time();
        if ($data['freight_is_type'] == 1) {  //全国
            $res = Db::name('freight')->insertGetId($data);
        } elseif ($data['freight_is_type'] == 2) {
            $firstPrice = $data['firstPrice'];
            $againPrice = $data['againPrice'];
            unset($data['firstPrice']);
            unset($data['againPrice']);
            $res = Db::name('freight')->insertGetId($data);
            if ($res) {
                $details = [
                    ['freight_id' => $res, 'province_name' => '新疆维吾尔自治区', 'freight_first_price' => $firstPrice[0], 'freight_continued_price' => $againPrice[0]],
                    ['freight_id' => $res, 'province_name' => '西藏自治区', 'freight_first_price' => $firstPrice[1], 'freight_continued_price' => $againPrice[1]],
                    ['freight_id' => $res, 'province_name' => '内蒙古自治区', 'freight_first_price' => $firstPrice[2], 'freight_continued_price' => $againPrice[2]]
                ];
                $res = Db::name('freight_class')->insertAll($details);
            }
        } elseif ($data['freight_is_type'] == 3) {
            $selectId = $data['selectId'];
            unset($data['selectId']);
            $res = Db::name('freight')->insertGetId($data);
            if ($res) {
                $details = [];
                foreach ($selectId as $value) {
                    $city = DB::name('cities')->where('cityid', $value)->find();
                    if (empty($city)) continue;
                    $province = DB::name('provinces')->where('provinceid', $city['provinceid'])->find();
                    $details[] = ['freight_id' => $res, 'province_name' => $province['province'], 'city_name' => $city['city'], 'city_id' => implode(',', $selectId)];
                }
                $res = Db::name('freight_class')->insertAll($details);
            }
        }
        if ($res) {
            return returnJson(1, '添加成功');
        }
        return returnJson(0, '添加失败');
    }

    /**
     *  添加上门模板
     */
    public function addHomeService()
    {
        $data = Request::instance()->post();
        $data['freight_merchant_id'] = session('merchant.merchant_id');
        $data['freight_tpl_type'] = 2;
        $data['freight_create_time'] = $data['freight_update_time'] = time();
        $price = $data['price'];
        unset($data['price']);
        $selectId = $data['selectId'];
        unset($data['selectId']);
        $res = Db::name('freight')->insertGetId($data);
        if ($res) {
            $details = [];
            $areas = [];
            foreach ($selectId as $value) {
                $area = DB::name('areas')->where('areaid', $value)->find();
                if (empty($area)) continue;
                if (isset($areas[$area['cityid']])) {
                    $areas[$area['cityid']] .= ',' . $area['area'];
                } else {
                    $areas[$area['cityid']] = $area['area'];
                }
            }
            foreach ($areas as $k => $v) {
                $city = DB::name('cities')->where('cityid', $k)->find();
                $province = DB::name('provinces')->where('provinceid', $city['provinceid'])->find();
                $details[] = ['freight_id' => $res, 'province_name' => $province['province'], 'city_name' => $city['city'],
                    'region_name' => $v, 'freight_door_cost' => $price, 'region_id' => implode(',', $selectId)];
            }
            $res = Db::name('freight_class')->insertAll($details);
            if ($res) {
                return returnJson(1, '添加成功');
            }
            return returnJson(0, '添加失败');
        }
    }

    /**
     *  编辑快递模板
     */
    public function editExpress()
    {
        $data = Request::instance()->post();
        $id = $data['id'];
        unset($data['id']);
        $data['freight_update_time'] = time();
        if ($data['freight_is_type'] == 1) {  //全国
            $res = Db::name('freight')->where('freight_id', $id)->update($data);
        } elseif ($data['freight_is_type'] == 2) {
            $firstPrice = $data['firstPrice'];
            $againPrice = $data['againPrice'];
            unset($data['firstPrice']);
            unset($data['againPrice']);
            $res = Db::name('freight')->where('freight_id', $id)->update($data);
            if ($res) {
                Db::name('freight_class')->where('freight_id', $id)->where('province_name', '新疆维吾尔自治区')->update(['freight_first_price' => $firstPrice[0], 'freight_continued_price' => $againPrice[0]]);
                Db::name('freight_class')->where('freight_id', $id)->where('province_name', '西藏自治区')->update(['freight_first_price' => $firstPrice[1], 'freight_continued_price' => $againPrice[1]]);
                Db::name('freight_class')->where('freight_id', $id)->where('province_name', '内蒙古自治区')->update(['freight_first_price' => $firstPrice[2], 'freight_continued_price' => $againPrice[2]]);
            }
        } elseif ($data['freight_is_type'] == 3) {
            $selectId = $data['selectId'];
            unset($data['selectId']);
            $res = Db::name('freight')->where('freight_id', $id)->update($data);
            if ($res) {
                Db::name('freight_class')->where('freight_id', $id)->delete();
                $details = [];
                foreach ($selectId as $value) {
                    $city = DB::name('cities')->where('cityid', $value)->find();
                    if (empty($city)) continue;
                    $province = DB::name('provinces')->where('provinceid', $city['provinceid'])->find();
                    $details[] = ['freight_id' => $id, 'province_name' => $province['province'], 'city_name' => $city['city']];
                }
                $res = Db::name('freight_class')->insertAll($details);
            }
        }
        if ($res) {
            return returnJson(1, '添加成功');
        }
        return returnJson(0, '添加失败');
    }

    /**
     *  编辑上门模板
     */
    public function editHomeService()
    {
        if (Request::instance()->isAjax()) {
            $data = Request::instance()->post();
            $selectId = $data['selectId'];
            $res = Db::name('freight')->where('freight_id', $data['id'])->update(['freight_name' =>$data['freight_name'], 'freight_update_time' => time()]);
            if ($res) {
                Db::name('freight_class')->where('freight_id', $data['id'])->delete();
                $details = [];
                $areas = [];
                foreach ($selectId as $value) {
                    $area = DB::name('areas')->where('areaid', $value)->find();
                    if (empty($area)) continue;
                    if (isset($areas[$area['cityid']])) {
                        $areas[$area['cityid']] .= ',' . $area['area'];
                    } else {
                        $areas[$area['cityid']] = $area['area'];
                    }
                }
                foreach ($areas as $k => $v) {
                    $city = DB::name('cities')->where('cityid', $k)->find();
                    $province = DB::name('provinces')->where('provinceid', $city['provinceid'])->find();
                    $details[] = ['freight_id' => $data['id'], 'province_name' => $province['province'], 'city_name' => $city['city'],
                        'region_name' => $v, 'freight_door_cost' => $data['price'], 'region_id' => implode(',', $selectId)];
                }
                $res = Db::name('freight_class')->insertAll($details);
                if ($res) {
                    return returnJson(1, '添加成功');
                }
                return returnJson(0, '添加失败');
            }
        }
        $id = input('id');
        $freight = DB::name('freight')->where('freight_id', $id)->find();
        if ($freight['freight_merchant_id'] != session('merchant.merchant_id')) {
            exit('403');
        }
        $areas = [];
        $details = DB::name('freight_class')->where('freight_id', $id)->field('region_name, freight_door_cost, region_id')->select();
        foreach ($details as $detail) {
            $areas[] = $detail['region_name'];
        }
        $freight['areas'] = implode(',', $areas);
        $freight['area_ids'] = $detail['region_id'];
        $freight['price'] = $detail['freight_door_cost'];
        return view('homeserviceedit', ['freight' => $freight]);
    }

    //添加运费模板页面
    public function do_adds(){
        dump(input('post.'));die();
        $data['freight_name'] = input('post.freight_name');
        $data['freight_tpl_type'] = '2';
        $data['province'] = input('post.province_name');
        $data['city'] = input('post.city_name');
        $data['freight_distribution_region_address'] = input('post.region');
        $data['freight_first_price'] = input('post.freight_first_price');
        $data['freight_continued_price'] = input('post.freight_continued_price');
        $data['freight_door_cost'] = input('post.freight_door_cost');
        $data['freight_create_time'] = time();
        $data['freight_merchant_id'] = session('merchant.merchant_id');
        $ret = SelfTakeModel::self_take_add($data);
        if(!$ret){
            return returnJson('', 300, '添加自提点失败');
        }
        return returnJson('', 300, '添加自提点成功');
    }

    //修改运费模板数据
    public function do_edit(){
        $freight_id = input('freight_id');
        $freight_list = Freight::get($freight_id);
        if(!$freight_list){
            return returnJson('', 300, '该自提点不存在');
        }
        if($freight_list['self_take_merchant_id'] != session('merchant.merchant_id')){
            return returnJson('', 300, '该自提点不属于你');
        }
        $where =[
            'freight_id' => $freight_id,
        ];
        $data['freight_name'] = input('post.freight_name');
        $data['freight_tpl_type'] = input('post.freight_tpl_type');
        $data['freight_distribution_province_address'] = input('post.province');
        $data['freight_distribution_city_address'] = input('post.city');
        $data['freight_distribution_region_address'] = input('post.region');
        $data['freight_first_price'] = input('post.freight_first_price');
        $data['freight_continued_price'] = input('post.freight_continued_price');
        $data['freight_door_cost'] = input('post.freight_door_cost');
        $data['freight_update_time'] = time();
        $data['freight_merchant_id'] = session('merchant.merchant_id');
        $ret = FreightModel::update($data, $where);
        if(!$ret){
            return returnJson('', 300, '修改自提点失败');
        }
        return returnJson('', 200, '修改自提点成功');
    }
    //删除商户快递模板
    public static function freight_del(){
        $freight_id = input('post.freight_id');
        $where =[
            'freight_id' => $freight_id,
        ];
        $data['freignt_is_delete'] = '1';
        $freight = FreightModel::update($data, $where);
        if(!$freight){
            return false;
        }
        return true;
    }

    public function del()
    {
        $id = input('post.id');
        $data['freignt_is_delete'] = 1;
        $data['freight_update_time'] = time();
        $res = Db::name('freight')->where('freight_id', $id)->update($data);
        if(!$res){
            return returnJson(0,'删除失败');
        }
        return returnJson(1, '删除成功');
    }
}